function update_profile(row) {
    try {
        var first_effective_index = $("#user-table").find("tr:first td").size() - 5;

        var identity = $(row).find("td:first p").text().trim();
        var user_passwd = $(row).find("td:nth-child(2) p").text().trim();

        var screen_name = $(row).find("td").eq(first_effective_index).find("input").val();
        if (typeof screen_name == "undefined") {
            screen_name = "";
        } else {
            screen_name = screen_name.trim();
        }
        var desc = $(row).find("td p").eq(first_effective_index+1).text().trim();
        var tags = $(row).find("td p").eq(first_effective_index+2).text().trim();
        var avatar = $(row).find("td p").eq(first_effective_index+3).text().trim();

        if (tags.length > 0) {
            tags = tags.replace(/#/g, ',');
        }

        if (screen_name.length > 0 || desc.length > 0 || tags.length > 0 || avatar.length > 0) {
            var cmd = sprintf('-i "%s" -v "%s" -s "%s" -d "%s" -a "%s" -t "%s"',
                              identity, user_passwd, screen_name, desc, avatar, tags);

            $(row).find('td:last').text('正在更新profile: ' + cmd);

            ++profile_updates_in_execution;
            $.ajax({
                url: 'index.php?ajax',
                type: 'post',
                data: {'cmd': cmd},
                success: function(data) {
                    console.log(data);
                    //if (typeof jQuery.parseJSON(data) == 'object') {
                        var data = jQuery.parseJSON(data);
                    //}
                    $(row).find('td:last').text('ajax success: ' + data);
                    --profile_updates_in_execution;

                    if (data.update_status == 'update profile success') {
                        insert_to_db(row);
                        $(row).find('td:last').text(data.update_status);
                    }
                    else {
                        $(row).find('td:last').text(data);
                    }
                },
                error: function(data) {
                    $(row).find('td:last').text("error: " + data);
                    --profile_updates_in_execution;
                    alert('update profiled failed');
                }
            });
            //$(row).find('td:last').load(
            //    'index.php?ajax',
            //    {'cmd': cmd},
            //    function() {
            //        --profile_updates_in_execution;
            //    }
            //);
        }

    } catch(err) {
        alert('很不幸，update_profile 出错啦:' + err);
    }
}

function polite_update_profile(row) {
    if (profile_updates_in_execution < 5) {
        update_profile(row);
    } else {
        $(row).find('td:last').text('等待更新profile...');
        setTimeout(function() {
                       polite_update_profile(row);  
                   }, 5000);
    }
}

function insert_to_db(row) {
    try {
        $(row).children("td:last").text('写入数据库中...');

        var last_effective_index = $("#user-table").find("tr:first td").size() - 5;
        // Get the column names to DB, update string, insert string and finally the SQL statment
        var str_column = '';
        var str_update = '';
        var str_insert = '';
        var columns = $("#user-table").find("tr:first td").slice(0, last_effective_index);

        var items = $(row).find('td p');

        $(columns).each(function(index, value) {
            str_column += $(value).text() + ',';
            str_insert += sprintf('"%s",', $($(items).get(index)).text());
            str_update += sprintf('%s = "%s",',
                                  $(value).text(),
                                  $($(items).get(index)).text());
        });

        str_column = str_column.slice(0, -1);
        str_insert = str_insert.slice(0, -1);
        str_update = str_update.slice(0, -1);

        var sql = sprintf('insert into local_user(%s) values(%s) on duplicate key update %s',
                          str_column, str_insert, str_update);

        // Use ajax to send the SQL request
        $.ajax({
            url: 'mysql.php',
            type: "POST",
            data: {
                sql: sql
            },
            success: function(data) {
                //var data = jQuery.parseJSON(data);
                //$(row).find('td:last').append(data.success_info);
                $(row).find('td:last').append('<br />' + data);
            },
            error: function(data) {
                $(row).find('td:last').append('<br />' +"mysql error: " + data);
            }
        });
    } catch(err) {
        alert('很不幸，insert_to_db 出错了:' + err);
    }
}

function update_row(btn) {
    //insert_to_db($(btn).parents('tr:first'));
    update_profile($(btn).parents('tr:first'));
}

var profile_updates_in_execution = 0;

$(document).ready(function() {
    $("#user-table").find('tr:gt(0)').each(function(index, data) {
        //var identity = $(data).find('td:first').text();
        //var passwd = $(data).find('td:nth-child(2)').text();
        var td_count = $(data).find('td').length -1;
        for (i=0; i <10; i++) {
            var current_td = $(data).find(sprintf('td:nth-child(%s)', i+1))[0];
            if (i==6) {
                //var current_td_text = $(data).find(sprintf('td:nth-child(%s)', i+1))[0].find('input').val();
                current_td_text = $(current_td).find('input').val();
                var appended_p_element = sprintf('<p><input type="text" class="editable" value=%s></p>', current_td_text);
                $(current_td).html(appended_p_element);
            }
            else {
            var current_td_text = $(current_td).text();
            var appended_p_element = sprintf('<p>%s</p>', current_td_text);
            $(current_td).html(appended_p_element);

            if (i!=10)
                $(current_td).css({'width':'80px', 'word-break':'break-all'});
            else
                $(current_td).css({'width':'100px', 'word_break':'break-all'});

            if (i==0) {
                second_td = $(data).find(sprintf('td:nth-child(%s)', i+2))[0];
                var authorize_url = sprintf('<br /><a target= "_blank" href="../manual_auth/index.php?identity=%s&passwd=%s">授权</a>', current_td_text, $(second_td).text());
                $(current_td).append(authorize_url);
            }
            }
        }

        //var authorize_url = sprintf('<br /><a target= "_blank" href="http://ipshow.iniming.com/qq_manual.php?identity=%s&passwd=%s">授权</a>', identity, passwd);
        
        //$(data).find('td:last').append(authorize_url);
        
        $(data).find('td:last').dblclick(
            function(event) {
                $(event.target).html('<button onclick="update_row(this);">update</button>');
            });
    });

    $("#submit-ajax").click(function() {
        // Do the uploading here, using AJAX
        try {
            var table = $("#user-table");
            var status_col_index = $(table).find("tr:first td").size() - 1;
            var all_row = $(table).find('tr:gt(0)');
            $(all_row).each(function(index, row) {
                polite_update_profile(row);
            });

        } catch (err) {
            alert('很不幸，出错了:' + err);
        }
    });

});
        
